package com.edevp.common.redis.util;

import com.edevp.common.core.util.ServiceHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author lean
 * @date 2022-07-06 3:05 PM
 **/
@Component
@RequiredArgsConstructor
public class RedisUtil {
	/** 静态工厂方法 **/
	public static RedisUtil getInstance() {
		return ServiceHelper.getBean(RedisUtil.class);
	}
	private final RedisTemplate  redisTemplate;

	public RedisTemplate getRedisTemplate(){
		this.redisTemplate.setEnableTransactionSupport(false);
		return this.redisTemplate;
	}

	/**
	 * 普通缓存放入并设置时间
	 * @param key 键
	 * @param value 值
	 * @param timeout 时间(秒) time要大于0 如果time小于等于0 将设置无限期
	 * @return true成功 false 失败
	 */
	public <T> boolean set(String key,T value,long timeout){
		ValueOperations<String, T> operation = redisTemplate.opsForValue();
		operation.set(key, value, timeout, TimeUnit.SECONDS);
		return true;
	}

	public boolean del(String key){
		redisTemplate.delete(key);
		return true;
	}

	public <T> T get(String key){
		ValueOperations<String, T> operation = redisTemplate.opsForValue();
		return operation.get(key);
	}
}
